<template>
  <div>
    <puplic-modal
      :publicVisible="publicVisible"
      :title="title"
      modalStyle="addEditSupportModal"
      width="840px"
      @cancel="cancel"
      @handleOk="handleOk"
    >
      <div slot="content" class="content">
        <div class="title flex align-center">
          <div class="icon"></div>
          选择要复制的场所分类
        </div>

        <div class="tree-wrap flex column">
          <div class="search-group" style="padding: 0 0.1rem 0 0.2rem; background: var(--theme-content-item-bg)">
            <div class="input-wrap" style="width: 100%">
              <div class="input-item" style="padding: 0; width: 100%">
                <a-input v-model="value" :maxLength="15" placeholder="请输入分类名称" @pressEnter="onSearch">
                  <a-icon slot="prefix" class="search-icon" type="search" />
                  <a-button slot="suffix" class="searchBtn" style="margin-right: 0" type="primary" @click="onSearch"
                    >搜索</a-button
                  >
                </a-input>
              </div>
            </div>
          </div>

          <a-tree
            :autoExpandParent="autoExpandParent"
            :checkStrictly="checkStrictly"
            :checkedKeys="checkedKeys"
            :expandedKeys="iExpandedKeys"
            :replace-fields="replaceFields"
            :selectable="false"
            :treeData="departTree"
            checkable
            class="f1"
            multiple
            @check="onCheck"
            @expand="onExpand"
          >
            <a-icon slot="switcherIcon" type="down" />
            <template #title="{ informationName }">
              <span v-if="informationName.indexOf(value) > -1">
                {{ informationName.substr(0, informationName.indexOf(value)) }}
                <span style="color: #ecf0f1; background: #74b9ff">{{ value }}</span>
                {{ informationName.substr(informationName.indexOf(value) + value.length) }}
              </span>
              <span v-else>{{ informationName }}</span>
            </template>
          </a-tree>

          <div class="drawer-bootom-button">
            <a-dropdown :trigger="['click']" placement="topCenter">
              <a-menu slot="overlay" class="much">
                <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
                <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
              </a-menu>
              <a-button class="searchBtn"> 树操作 <a-icon type="up" /> </a-button>
            </a-dropdown>
          </div>
        </div>

        <div class="title flex align-center">
          <div class="icon"></div>
          已存在相同名称的检查分类
          <div class="wraming">选择后新的检查内容会覆盖之前的检查内容，且不可恢复，请谨慎操作</div>
        </div>

        <div v-if="tree_2_empty" class="tree-wrap flex align-center justify-center">
          <a-empty>
            <span slot="description" style="color: #78ade3"> 未查询到重复值! </span>
          </a-empty>
        </div>
        <div v-else class="tree-wrap flex column">
          <div class="search-group" style="padding: 0 0.1rem 0 0.2rem; background: var(--theme-content-item-bg)">
            <div class="input-wrap" style="width: 100%">
              <div class="input-item" style="padding: 0; width: 100%">
                <a-input v-model="value2" :maxLength="15" placeholder="请输入分类名称" @pressEnter="onSearch2">
                  <a-icon slot="prefix" class="search-icon" type="search" />
                  <a-button slot="suffix" class="searchBtn" style="margin-right: 0" type="primary" @click="onSearch2"
                    >搜索</a-button
                  >
                </a-input>
              </div>
            </div>
          </div>

          <div v-if="departTree2.length == 0" class="f1 flex align-center justify-center">
            <span style="color: #80b5de">请勾选上面树进行查询</span>
          </div>
          <a-tree
            v-else
            :autoExpandParent="autoExpandParent2"
            :checkStrictly="checkStrictly2"
            :checkedKeys="checkedKeys2"
            :expandedKeys="iExpandedKeys2"
            :replace-fields="replaceFields2"
            :selectable="false"
            :treeData="departTree2"
            checkable
            class="f1"
            multiple
            @check="onCheck2"
            @expand="onExpand2"
          >
            <a-icon slot="switcherIcon" type="down" />
            <template #title="{ informationName }">
              <span v-if="informationName.indexOf(value2) > -1">
                {{ informationName.substr(0, informationName.indexOf(value2)) }}
                <span style="color: #ecf0f1; background: #74b9ff">{{ value2 }}</span>
                {{ informationName.substr(informationName.indexOf(value2) + value2.length) }}
              </span>
              <span v-else>{{ informationName }}</span>
            </template>
          </a-tree>

          <div class="drawer-bootom-button">
            <a-dropdown :trigger="['click']" placement="topCenter">
              <a-menu slot="overlay" class="much">
                <a-menu-item key="5" @click="expandAll2">展开所有</a-menu-item>
                <a-menu-item key="6" @click="closeAll2">合并所有</a-menu-item>
              </a-menu>
              <a-button class="searchBtn"> 树操作 <a-icon type="up" /> </a-button>
            </a-dropdown>
          </div>
        </div>
      </div>
    </puplic-modal>
  </div>
</template>
<script>
import puplicModal from '@/components/publicModal'
import { getAction, postAction } from '@/api/manage'
export default {
  components: { puplicModal },
  name: 'addEditSupportModal',
  data() {
    return {
      title: '一键复制【场所内部检查】',
      publicVisible: false,
      records: {},

      value: '', // tree search value
      dataList: [],

      departTree: [],

      checkedKeys: [],
      iExpandedKeys: [],
      checkStrictly: false,
      autoExpandParent: true,
      replaceFields: {
        key: 'id',
        title: 'informationName',
      },

      value2: '', // tree search value
      dataList2: [],

      departTree2: [],

      allTreeKeys2: [],
      checkedKeys2: [],
      iExpandedKeys2: [],
      checkStrictly2: false,
      autoExpandParent2: true,
      replaceFields2: {
        key: 'id',
        title: 'informationName',
      },

      tree_2_empty: false,
    }
  },
  mounted() {},
  methods: {
    show(records) {
      this.records = records
      this.loadTree(records.industryInformationId)
      this.publicVisible = true
    },

    // * 树的筛选方法 开始
    onSearch() {
      const expanded = this.dataList
        .map((item) => {
          if (item.informationName.indexOf(this.value) > -1) {
            return this.getParentKey(item.id, this.departTree)
          }
          return null
        })
        .filter((item, i, self) => {
          if (item && self.indexOf(item) === i) {
            return item
          }
        })
      this.iExpandedKeys = expanded
      this.autoExpandParent = true
    },

    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },

    generateList(tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        const id = node.id
        const informationName = node.informationName
        this.dataList.push({
          id,
          informationName: informationName,
        })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    // * 树的筛选方法 结束

    async loadTree(notId) {
      let { result } = await getAction('/industry/information/tree', { notId })
      this.allTreeKeys = []
      this.departTree = result

      this.getAllKeys(result) // * 用于右下角树操作功能
      this.generateList(this.departTree) // * 用作搜索 书中包含关键字的方法
    },

    // * 用于右下角树操作功能
    getAllKeys(tree) {
      tree.forEach((item) => {
        if (item.id) this.allTreeKeys.push(item.id)
        if (item.children) {
          this.getAllKeys(item.children)
        }
      })
    },

    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },

    closeAll() {
      this.iExpandedKeys = []
    },

    // * 树方法
    onCheck(checkedKeys, info) {
      let { id } = info.node.dataRef
      const indexToRemove = this.checkedKeys.findIndex((item) => item === id)
      if (indexToRemove == -1) {
        this.checkedKeys = checkedKeys
        this.loadTree2()
      } else {
        this.checkedKeys = checkedKeys
        if (this.checkedKeys.length == 0) this.tree_2_empty = false
      }
    },

    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    // * 树的筛选方法 开始
    generateList2(tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        const id = node.id
        const informationName = node.informationName
        this.dataList2.push({
          id,
          informationName: informationName,
        })
        if (node.children) {
          this.generateList2(node.children)
        }
      }
    },

    onSearch2() {
      const expanded = this.dataList2
        .map((item) => {
          if (item.informationName.indexOf(this.value2) > -1) {
            return this.getParentKey2(item.id, this.departTree)
          }
          return null
        })
        .filter((item, i, self) => {
          if (item && self.indexOf(item) === i) {
            return item
          }
        })
      this.iExpandedKeys2 = expanded
      this.autoExpandParent2 = true
    },

    getParentKey2(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey2(key, node.children)) {
            parentKey = this.getParentKey2(key, node.children)
          }
        }
      }
      return parentKey
    },
    // * 树的筛选方法 结束

    async loadTree2() {
      let { result } = await postAction('/industry/information/examine_name_tree', {
        examineId: this.records.id,
        informationIdList: this.checkedKeys,
      })
      if (result.length == 0) {
        this.tree_2_empty = true
        return
      }

      this.tree_2_empty = false
      this.allTreeKeys2 = []
      this.departTree2 = result

      this.getAllKeys2(result) // * 用于右下角树操作功能
      this.checkedKeys2 = this.allTreeKeys2
      this.iExpandedKeys2 = this.allTreeKeys2
      this.generateList2(this.departTree) // * 用作搜索 书中包含关键字的方法
    },

    // * 用于右下角树操作功能
    getAllKeys2(tree) {
      tree.forEach((item) => {
        if (item.id) this.allTreeKeys2.push(item.id)
        if (item.children) {
          this.getAllKeys2(item.children)
        }
      })
    },

    expandAll2() {
      this.iExpandedKeys2 = this.allTreeKeys2
    },

    closeAll2() {
      this.iExpandedKeys2 = []
    },

    // * 树方法
    onCheck2(checkedKeys, info) {
      this.checkedKeys2 = checkedKeys
      // let { id } = info.node.dataRef
      // const indexToRemove = this.checkedKeys2.findIndex((item) => item === id)
      // if (indexToRemove == -1) {
      //   this.checkedKeys2 = checkedKeys
      // } else {
      //   this.checkedKeys2 = checkedKeys
      //   this.cancel_tree_2_list.push(id)
      // }
    },

    onExpand2(expandedKeys) {
      this.iExpandedKeys2 = expandedKeys
      this.autoExpandParent2 = false
    },

    async handleOk() {
      let checked =
        this.allTreeKeys2.length === 0
          ? this.checkedKeys
          : this.checkedKeys.filter((item) => !this.allTreeKeys2.includes(item))
      checked = checked.concat(this.checkedKeys2)

      let res = await postAction('/industry/information/cope', {
        examineId: this.records.id,
        informationIdList: checked,
      })
      if (res.code == 200) {
        this.$message.success(res.message)
        this.$emit('refresh')
        this.$emit('loadTree')
        this.cancel()
        return
      }
      this.$message.error(res.message)
      this.cancel()
    },

    cancel() {
      this.value = ''
      this.selectedKeys = []
      this.checkedKeys = []
      this.iExpandedKeys = []

      this.value2 = ''
      this.departTree2 = []
      this.iExpandedKeys2 = []
      this.selectedKeys2 = []
      this.checkedKeys2 = []

      this.publicVisible = false
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@/assets/less/common.less';

/deep/ .content {
  padding: 20px;
}
/deep/ .modalFooter > div {
  padding-top: 0 !important;
  // height: 20px !important;
}

.title {
  font-size: 16px;
  font-family: PingFang SC-Bold, PingFang SC;
  font-weight: bold;
  color: var(--theme-modal-label-value-color);
  .icon {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 5px;
    background: #80b5eb;
  }

  .wraming {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #f8df63;
    margin-left: 5px;
  }
}

.tree-wrap {
  height: 320px;
  background: var(--theme-content-item-bg);
  margin: 16px 0;
  overflow-y: scroll;

  position: relative;
  .btn-group {
    padding: 0.2rem 0 0 0.2rem;
    .btn-common {
      width: 1.2rem;
      height: 0.4rem;
      line-height: 0.4rem;
      text-align: center;
      background: #1388ff;
      border-radius: 0.04rem;
      font-size: 0.16rem;
      font-weight: bold;
      color: #0b3f73;
      cursor: pointer;
      &:nth-child(2) {
        margin-left: 0.2rem;
      }
    }
  }

  .drawer-bootom-button {
    position: absolute;
    right: 0.1rem;
    bottom: 0.1rem;
    border-radius: 0.04rem;
  }
}

.m-h-0 {
  min-height: 0;
}
</style>
